package com.elli0tt.config;

import com.elli0tt.io.Resources;
import com.elli0tt.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author elli0tt
 * @version 1.0
 * @className XMLConfigBuilder.java
 * @description sqlMapConfig.xml 解析器
 * @createTime 2020-08-28 21:57:31
 */
public class XMLConfigBuilder {

    private final Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 解析配置文件并封装到 {@link Configuration}
     *
     * @param inputStream 配置文件字节输入流对象
     * @return {@link Configuration}
     */
    public Configuration parse(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        // <configuration>
        Element rootElement = document.getRootElement();
        initDataSource(rootElement);
        // 解析 mapper.xml
        initMappedStatementMap(rootElement);

        return configuration;
    }

    /**
     * 初始化 {@link Configuration} 中的 dataSource 成员变量
     *
     * @param rootElement 根标签元素
     */
    private void initDataSource(Element rootElement) throws PropertyVetoException {
        List<Element> propertyElements = rootElement.selectNodes("dataSource/property");
        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);
    }

    /**
     * 初始化 {@link Configuration} 中的 mappedStatementMap
     *
     * @param rootElement 根标签元素
     * @throws Exception
     */
    private void initMappedStatementMap(Element rootElement) throws Exception {
        List<Element> mapperElements = rootElement.selectNodes("mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element mapperElement : mapperElements) {
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream mapperStream = Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parse(mapperStream);
        }
    }
}
